package main

import (
	"github.com/gorilla/mux"
	"log"
	"net/http"
	"short_domain/config"
	_ "short_domain/init"
	"short_domain/models"
)

func main() {
	//restful
	router := mux.NewRouter().StrictSlash(true)
	//生成短链
	router.HandleFunc("/address", address).Methods("GET")
	//获取短链信息
	router.HandleFunc("/{short}", visit)

	//设置监听的端口
	err := http.ListenAndServe("0.0.0.0:8088", router)
	if err != nil {
		log.Fatal("ListenAndServe failure: ", err)
	}
}

func address(response http.ResponseWriter, request *http.Request) {
	if domain,err := models.GetDomainByUrl(request.URL.RawQuery); err == nil {
		response.Write([]byte(config.DomainConf.Short + domain.Short))
		return
	}
	response.WriteHeader(400)
	response.Write([]byte("failure"))
}

func visit(response http.ResponseWriter, request *http.Request) {
	vars := mux.Vars(request)
	short := vars["short"]

	if domain,err := models.GetDomainByShort(short); err == nil {
		http.Redirect(response, request, config.DomainConf.Host + "?" + domain.Url, http.StatusFound)
		return
	}
	response.WriteHeader(400)
	response.Write([]byte("failure"))
}
